
<html>
<head><title>Calculator</title></head>
<body>

<h1>Calculator</h1>
(Ver 1.0 4/6/2012 by Wade Norris)<br />
Type an expression in the following box (e.g., 10.5+20*3/25).
<p>
<form method="GET">
<input type="text" name="expr"><input type="submit" value="Calculate">
</form>
</p>
<ul>
<li>Only numbers and +,-,* and / operators are allowed in the expression.
<li>The evaluation follows the standard operator precedence.
<li>The calculator does not support parentheses.
<li>The calculator handles invalid input "gracefully". It does not output PHP error messages.
</ul>
Here are some(but not limit to) reasonable test cases:
<ol>
  <li> A basic arithmetic operation:  3+4*5=23 </li>
  <li> An expression with floating point or negative sign : -3.2+2*4-1/3 = 4.46666666667, 3+-2.1*2 = -1.2 </li>
  <li> Some typos inside operation (e.g. alphabetic letter): Invalid input expression 2d4+1 </li>
</ol>
<?

ini_set("display_errors", "0");

// Custome Error Handler
function errorHandler($errno, $errstr, $errfile, $errline)
{	
	die('Invalid expression ' . $_GET['expr'] . '.');
	
    // Shouldn't make it here since we used die above
	// but just in case this return will prevent default
	// error handler from executing.
    return true;
}
set_error_handler("errorHandler");

// Compute value and display response
if(isset($_GET['expr']))
{
	echo '<h2>Result</h2>';
	
	// Should match a number and operator any number of times followed by at least one number.
	if(!preg_match("/^((-?[1-9][0-9]*(\.[0-9]*)?)[+\-*\/])*(-?[1-9][0-9]*(\.[0-9]*)?)$/", $_GET['expr']))
	//TODO Accept numbers with leading 0s?
	{
		die('Invalid expression ' . $_GET['expr'] . '.');
	}
	
	try {
		eval('$output = ' . $_GET['expr'] . ';');
	} catch (Exception $e) {
		die('Invalid expression ' . $_GET['expr'] . '.');
	}
	
	// Output result if we make it here without exception
	echo $_GET['expr'] . ' = ' . $output;
}
?>
</body>
</html>

